package com.atguigu.gulimall.order.listener;

import com.atguigu.gulimall.order.entity.OrderEntity;
import com.atguigu.gulimall.order.service.OrderService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

import static com.atguigu.gulimall.order.config.GuliMallRabbitConfig.ORDER_RELEASE_QUEUE;

/** RabbitMQ 用户如果超时未支付，关闭订单
 * @Author ShiJieLin
 * @Date 2022/5/2 11:29
 * @Version 1.0
 */
@RabbitListener(queues = {ORDER_RELEASE_QUEUE})
@Component
@Slf4j
public class OrderCloseListener {

    public static final String ORDER_RELEASE_QUEUE1 = ORDER_RELEASE_QUEUE;
    @Autowired
    private OrderService orderService;

    @RabbitHandler
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {

        log.info("收到了关闭订单的消息----》{}", orderEntity);

        try {
            // 关闭订单，如果成功就直接确认
            orderService.closeOrder(orderEntity);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);

        }catch (Exception e){
            // 关闭订单失败，将消息重新放回队列
           log.info("关闭订单失败，错误信息是：{}", e);
           channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
